﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace iLangl.BusinessModel.DAL.XMLStorage
{
	public class AlertDAL : BaseStorageDAL, IAlertDAL
	{
		#region IAlertDAL Members

		public void SaveAlert(ISerializedAlert alert,  IDbTransaction transaction)
		{
			dtoXmlStorage.AlertRow alertRow = Storage.Alert.FindById(alert.Id);

			bool isNew = (alertRow == null);

			if (isNew)
			{
				alertRow = Storage.Alert.NewAlertRow();
			}

			alertRow.Id = alert.Id;
			alertRow.DateCreated = alert.Created;
			alertRow.Content = alert.Content;
			alertRow.SiteId = alert.Source;
			alertRow.Severity = (int)alert.Severity;

			if (isNew)
			{
				Storage.Alert.AddAlertRow(alertRow);
			}

			if (alert.PackageIds != null)
			{
				foreach (String packageId in alert.PackageIds)
				{
					if (Storage.AlertPackages.FindByAlertIdPackageId(alert.Id, packageId) == null)
					{
						Storage.AlertPackages.AddAlertPackagesRow(alertRow, packageId);
					}

					dtoXmlStorage.PackageRow pr = Storage.Package.FindById(packageId);
					pr.IsSuccess = false;
				}
			}

			if (transaction == null)
			{
				AcceptChanges();
			}
		}


		public IList<ISerializedAlert> GetAlerts(TimeSpan from, TimeSpan to)
		{
			IList<ISerializedAlert> alerts = new List<ISerializedAlert>();

			foreach (dtoXmlStorage.AlertRow alertRow in Storage.Alert)
			{

				TimeSpan arts = new TimeSpan(alertRow.DateCreated.Ticks);
				if ((from <= arts) && (arts <= to))
				{
					ISerializedAlert alert = Facade.Instance.AlertManager.CreateSerializedAlert();
					alert.Id = alertRow.Id;
					alert.Created = alertRow.DateCreated;
					alert.Content = alertRow.Content;
					alert.Source = alertRow.SiteId;
					alert.Severity = (eSeverity)alertRow.Severity;
					alerts.Add(alert);
				}
			}

			return alerts;
		}

		#endregion
	}
}
